"use strict";
// 观察者+Store
// 注册监听函数
exports.__esModule = true;
var Store = /** @class */ (function () {
    function Store(reducer, iniState) {
        this.reducer = reducer;
        // 订阅列表
        this._listeners = new Array();
        this._state = iniState;
    }
    Store.prototype.getState = function () {
        return this._state;
    };
    /**
     * 订阅函数，返回一个退订函数
     * @param listenerCall
     */
    Store.prototype.subscribe = function (listenerCall) {
        var _this = this;
        this._listeners.push(listenerCall);
        return function () {
            // 退订函数的上下文中保留两个变量，一个是_listeners，一个是刚刚订阅的listener
            _this._listeners = _this._listeners.filter(function (listener) { return listener !== listenerCall; });
        };
    };
    /**
     * 修改state的值，同时通知每一个订阅者，向他们推送当前的state
     * @param action
     */
    Store.prototype.dispatch = function (action) {
        var _this = this;
        this._state = this.reducer(this._state, action);
        // 切记在调用监听函数时不可将本地的_state传入
        this._listeners.forEach(function (listener) { return listener(_this._state); });
    };
    return Store;
}());
exports.Store = Store;
/**
 * 圆
 */
var Circle = /** @class */ (function () {
    function Circle(radius) {
        this.radius = radius;
    }
    return Circle;
}());
var reducer = function (circle, action) {
    switch (action.type) {
        case 'SCALE_UP':
            return new Circle(circle.radius * action.payload);
        case 'SCALE_BACK':
            return new Circle(circle.radius / action.payload);
        default:
            return circle;
    }
};
// 圆周率
var PI = Math.PI;
var store = new Store(reducer, new Circle(10));
store.subscribe(function (circle) {
    console.log(circle === store.getState());
    console.log('area: ', Math.pow(circle.radius, 2) * PI);
    console.log('perimeter: ', circle.radius * 2 * PI);
});
store.dispatch({ type: 'SCALE_UP', payload: 2 });
store.dispatch({ type: 'SCALE_BACK', payload: 2 });
